// storedetail.js
var app = getApp()
var shihan = require('../../common/fetch');
var config = require('../../common/config');
var token = '';
var sceneres = {}
var winScale = 750 / app.data.deviceInfo.windowWidth
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    page_size: 20,
    foldword: '查看更多',
    toast_flag: false,
    foldflag: false,
    storepromore: true,
    storeproduct: [],
    listflag: true,
    has_more: true,
    dialogflag: true,
    defaults: 'https://img-oss.shihanbainian.com/shihan2/index/defaults.png'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    var that = this
    if (options.scene) {
      var scene = decodeURIComponent(options.scene).split('&'); //t=b||s&id=232&pid=1694
      if (scene && scene.length > 0) {
        for (var i = 0; i < scene.length; i++) {
          var str = scene[i].split('=')
          if (str[0] == 't') {
            if (str[1] == 'b') {
              this.setData({
                storetype: 'brand'
              })
            } else if (str[1] == 's') {
              this.setData({
                storetype: 'seller'
              })
            }
          } else if (str[0] == 'id') {
            this.setData({
              storeid: str[1]
            })
          } else if (str[0] == 'pid') {
            sceneres['partner_id'] = str[1]
          } else if (str[0] == 'cid') {
            sceneres['cid'] = str[1]
          }
        }
      }
    } else {
      if (options.type == 'brand') {
        this.setData({
          storetype: 'brand',
          storeid: options.id
        })
      } else {
        this.setData({
          storetype: 'seller',
          storeid: options.id
        })
      }
      if (options.cid) {
        sceneres['cid'] = options.cid
      }
      if (options.fansid) {
        sceneres['partner_id'] = options.fansid
      } else if (options.pid) {
        sceneres['partner_id'] = options.pid
      } else if (options.partner_id) {
        sceneres['partner_id'] = options.partner_id
      }
    }
    console.log(sceneres)
    var pages = getCurrentPages();
    if (pages.length >= 2) {
      var prevPage = pages[pages.length - 2];
      prevPage.setData({
        promotefresh: false
      })
    }

    that.getStore();
    app.wechatSwitch().then(function(wechat_switch) { //是否打开微信授权开关
      app.commonLogin(sceneres, wechat_switch)
    })
  },
  getStore: function () {
    var that = this;
    shihan.sendRequest(config.storedetail + that.data.storetype + '_id_' + that.data.storeid + '/' + that.data.page + '-' + that.data.page_size + '.html', 'POST', {}, {})
      .then(function (response) {
        if (response.data.code == 0 && that.data.page == 1) {
          wx.setNavigationBarTitle({
            title: response.data.data.sh_seller.sh_store_name
          })
          if (response.data.data.sh_seller.sh_description && response.data.data.sh_seller.sh_description.indexOf('<img') > 0) {
            response.data.data.sh_seller.sh_description = response.data.data.sh_seller.sh_description.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;" ')
          }
          that.setData({
            storedetail: response.data.data,
            collectionflag: response.data.data.sh_seller.sh_is_favorite == 1 ? true : false
          })
        }
        if (response.data.code == 0 && response.data.data.sh_products.length > 0) {
          for (var i = 0; i < response.data.data.sh_products.length; i++) {
            if (response.data.data.sh_products[i].sh_label.sh_location) {
              var pos = response.data.data.sh_products[i].sh_label
              pos['posa'] = pos.sh_location.split('_')[0];
              pos['posb'] = pos.sh_location.split('_')[1];
            }
            var productstr = response.data.data.sh_products[i]
            for (var b in productstr) {
              if (b&&b.indexOf("price") >= 0 && productstr[b]) {
                var pricestr = (JSON.stringify(productstr[b])).split('.')
                if (pricestr.length == 1) {
                  productstr[b] = productstr[b] + '.00'
                }
              }
            }
          }
          that.setData({
            listflag: true,
            has_more: true,
            page: that.data.page + 1,
            storeproduct: that.data.storeproduct.concat(response.data.data.sh_products)
          })
          if (that.data.storeproduct.length == response.data.data.sh_total_rows) {
            that.setData({
              listflag: false,
              has_more: false
            })
          }
          wx.reportAnalytics('page_stroe_home', {
            store_id: response.data.data.sh_seller.sh_id,
            store_name: response.data.data.sh_seller.sh_store_name
          })
        } else {
          that.setData({
            listflag: false,
            has_more: false
          })
        }
        // console.log(response);
      }, function (error) {
        console.log(error);
      });
  },
  addcollection: function(e) {
    var that = this
    token = wx.getStorageSync('token');
    var collecid = e.currentTarget.dataset.id
    if (token) {
      if (this.data.collectionflag == false) {
        shihan.sendRequest(config.add_favorite, 'POST', {
            id: collecid,
            type: 6
          })
          .then(function(response) {
            console.log(response);
            if (response.data.code == 0 || response.data.code == 1103) {
              that.data.storedetail.sh_seller.sh_is_favorite = 1
              that.setData({
                collectionflag: true,
                storedetail: that.data.storedetail
              })
              shihan.showToast.call(that, '添加收藏成功');
            } else if (response.data.code == 1101) {
              app.commonNoLogin()
            } else {
              shihan.showToast.call(that, response.data.msg);
            }
          }, function(error) {
            console.log(error);
          });
      } else {
        shihan.sendRequest(config.remove_favorite, 'POST', {
            id: collecid,
            type: 6
          })
          .then(function(response) {
            // console.log(response);
            if (response.data.code == 0) {
              that.data.storedetail.sh_seller.sh_is_favorite = 0
              that.setData({
                collectionflag: false,
                storedetail: that.data.storedetail
              })
              shihan.showToast.call(that, '取消收藏成功');
            } else if (response.data.code == 1101) {
              app.commonNoLogin()
            } else {
              shihan.showToast.call(that, response.data.msg);
            }
          }, function(error) {
            console.log(error);
          });
      }
    } else {
      app.commonNoLogin()
    }
  },
  viewgoodsDetail: function(e) {
    wx.navigateTo({
      url: '/pages/goodsdetail/goodsdetail?goodsid=' + e.currentTarget.dataset.id
    })
  },
  looklicense: function(e) {
    wx.navigateTo({
      url: '/pages/other/licensedetail/licensedetail?sub=' + JSON.stringify(e.currentTarget.dataset.sub)
    })
  },
  openfold: function() {
    if (this.data.foldflag == false) {
      this.setData({
        foldflag: true,
        foldword: '收起'
      })
    } else {
      this.setData({
        foldflag: false,
        foldword: '查看更多'
      })
    }
  },
  // 滚动计算滚动条距离
  onScroll: function(ev) {
    var scrollTop = ev.detail.scrollTop;
    if (scrollTop > 200) {
      this.setData({
        backToTop: true,
        backhomeheight: 156
      });
    } else {
      this.setData({
        backToTop: false,
        backhomeheight: 48
      });
    }
  },
  // 返回顶部
  onBackToTop: function() {
    this.setData({
      backToTop: false,
      scrollTop: 0,
      backhomeheight: 48
    })
  },
  backhome: function() {
    wx.switchTab({
      url: '/pages/home/home'
    });
  },
  loadMoreData: function() {
    if (this.data.listflag) {
      this.setData({
        listflag: false
      })
      this.getStore();
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var that = this, sharetit = '', shareurl;
    var customerId = wx.getStorageSync('customerId');
    if (that.data.storedetail.sh_seller.sh_share_title) {
      sharetit = that.data.storedetail.sh_seller.sh_share_title
    }
    shareurl = '/pages/storedetail/storedetail?home=1&type=seller&id=' + that.data.storedetail.sh_seller.sh_id + '&pid=' + customerId
    return {
      title: sharetit,
      path: shareurl,
      // imageUrl: that.data.storedetail.sh_seller.sh_share_image,
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
  }
})